//
//  MainViewController.m
//  DocumentWatermarking
//
//  Created by apple on 2017/11/9.
//  Copyright © 2017年 apple. All rights reserved.
//

#import "MainViewController.h"
#import "BusinessLicenseViewController.h"
#import "PhotoChoseViewController.h"
#import "FeatureSuggestionsViewController.h"
#import "HelpCenterViewController.h"
#import "DoubleImageOfTakePhotoController.h"
#import <UShareUI/UShareUI.h>
#import "PopShareView.h"
#import "PopClickView.h"
#import <WXApi.h>
#import <WeiboSDK.h>
#import <TencentOpenAPI/QQApiInterface.h>
#import "NetWorkRequest.h"
#import "VersionUpDataView.h"
#import "WatermarkContentViewController.h"
#import <KVNProgress.h>
#import "AppDelegate.h"
#import "AboutUsViewController.h"
#import <AVFoundation/AVFoundation.h>
#import "CupTwoView.h"
#import "SliderView.h"
#import "PhotoShowViewController.h"

#define HEIGHT  ([[UIScreen mainScreen] bounds].size.height)
#define WIDTH  ([[UIScreen mainScreen] bounds].size.width)

@interface MainViewController ()<UIGestureRecognizerDelegate>
{
    BOOL isDevicePositionFront;//前后摄像头
    BOOL isDoubleView;//单面还是双面
}

@property (weak, nonatomic) IBOutlet UIView *preView;//底部视图
@property (strong, nonatomic)  UIImageView *imageView;//图片
@property (nonatomic,strong)SliderView *slide;
@property (weak, nonatomic) IBOutlet UIView *bottomVeiw;
@property (weak, nonatomic) IBOutlet UIButton *selectImgButton;
@property (weak, nonatomic) IBOutlet UIButton *takePhotoButton;
@property (weak, nonatomic) IBOutlet UIButton *doubleButton;

@property(nonatomic,strong)UIImageView *waterMarkImageView;//显示水印

@property(nonatomic,strong)UIImageView *focusView;//聚焦图片

@property(nonatomic,strong)CupTwoView *maskView;//蒙版显示层 双面用
@property(nonatomic,strong)ImageShowView *currentSelectView;//当前选择的是上面还是下面  双面用
@property(nonatomic, nonnull,strong)UIView *showGrayView;//上面的显示遮罩层  双面用
@property(nonatomic, nonnull,strong)UIView *secondShowGrayView;//下面的显示遮罩层  双面用
@property(nonnull,strong)UIView *showTopTakePhotoView;//上面的显示拍照  双面用
@property(nonnull,strong)UIView *showSecondTakePhotoView;//下面的显示拍照   双面用

/**
 *  AVCaptureSession对象来执行输入设备和输出设备之间的数据传递
 */
@property (nonatomic, strong) AVCaptureSession* session;
/**
 *  输入设备
 */
@property (nonatomic, strong) AVCaptureDeviceInput* frontCameraInput;
/**
 *  输入设备
 */
@property (nonatomic, strong) AVCaptureDeviceInput* backCameraInput;
/**
 *  照片输出流
 */
@property (nonatomic, strong) AVCaptureStillImageOutput* stillImageOutput;
/**
 *  预览图层
 */
@property (nonatomic, strong) AVCaptureVideoPreviewLayer* previewLayer;

@property (nonatomic, assign) CGFloat currentZoomFactor;

/**
 *  记录开始的缩放比例
 */
@property(nonatomic,assign)CGFloat beginGestureScale;
/**
 * 最后的缩放比例
 */
@property(nonatomic,assign)CGFloat effectiveScale;

@property (nonatomic, strong) AVCaptureConnection *stillImageConnection;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *preViewWidth;

@end

@implementation MainViewController


- (void)viewWillAppear:(BOOL)animated{

    
    if (_session) {
        [_session startRunning];
    }
    
    if (self.doubleButton.selected) {
        [self.session startRunning];
        _maskView.shwoView.isSetImage = NO;
        _maskView.shwoView2.isSetImage = NO;
        _maskView.shwoView.image = nil;
        _maskView.shwoView2.image = nil;
        isDoubleView = YES;
        [self maskView];
        isDoubleView = YES;
        self.maskView.hidden = NO;
        [self createSecondTipView]; //创建下面的提示拍照视图
        
        _currentSelectView = _maskView.shwoView;
        
    }
    else{
        //点击了单面
        isDoubleView = NO;
        _imageView.image = nil;
    }

    
}

-(void)viewWillDisappear:(BOOL)animated{
    
    if (_session) {
        [_session stopRunning];
    }
}

- (void)viewDidLoad {
    [super viewDidLoad];
    UIButton *btn = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, 50, 50)];
    [btn setImage:[UIImage imageNamed:@"关闭闪光灯"] forState:UIControlStateNormal];
    [btn setImage:[UIImage imageNamed:@"开启闪光灯"] forState:UIControlStateSelected];
    [btn addTarget:self action:@selector(lightAction:) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *lightitem = [[UIBarButtonItem alloc]initWithCustomView:btn];

    UIButton *camerabtn = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, 50, 50)];
    [camerabtn setImage:[UIImage imageNamed:@"切换"] forState:UIControlStateNormal];
    [camerabtn addTarget:self action:@selector(changecapture:) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *cameraitem = [[UIBarButtonItem alloc]initWithCustomView:camerabtn];
    
    self.navigationItem.rightBarButtonItems = @[cameraitem,lightitem];

    [self prepare];
    [Tools acquireMediaType:AVMediaTypeVideo Auth:^(BOOL grant){
//        [_actiview stopAnimating];
//        [_actiview removeFromSuperview];
        
        if (grant) {
            //            [self.session startRunning];
            [self resetFocusAndExposureModes];
//            [self showfocus:_bgView.center];
        }
        else{
            
            UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"获取授权" message:@"您已设置关闭使用相机,请在设备的设置-隐私-相机中允许使用。" delegate:self cancelButtonTitle:nil otherButtonTitles:@"确定" ,nil];
            [alertView show];
            
        }
    }];
    
    
//    _slide = [[SliderView alloc]initWithFrame:CGRectMake(100, 100, 100, 100)];
//    [self.view addSubview:_slide];
    
//    [self requestNewVersion];
//
//    NSString *timeString = [[NSUserDefaults standardUserDefaults] objectForKey:kLaunchTimeShow];
//
//    if (timeString==nil) {
//
//        NSString *timeString = [Tools getNowTimeTimestamp];
//        [[NSUserDefaults standardUserDefaults] setObject:safeString(timeString) forKey:kLaunchTimeShow];
//        [[NSUserDefaults standardUserDefaults] synchronize];
//
//    }
//    else{
//
//        if ([self isTimeToLimitWeek]) {
//
//            NSString *timeString = [Tools getNowTimeTimestamp];
//            [[NSUserDefaults standardUserDefaults] setObject:safeString(timeString) forKey:kLaunchTimeShow];
//            [[NSUserDefaults standardUserDefaults] synchronize];
//            [self popshareWithshareTitle:@"觉得好用就分享给朋友们"];
//        }
//
//    }
    
//    self.title = @"首页";
//
//    [self rightButtonImage:nil RightButtonTitle:@"关于" rightButtonTarget:self rightButtonAction:@selector(shareAction)];
    
}

-(void)viewDidLayoutSubviews{
    [super viewDidLayoutSubviews];
   
}
/*
 *  创建预览
 */
-(void)prepare{
    
    NSError *error ;
    AVCaptureDevice *device = [self cameroWithPosition:AVCaptureDevicePositionBack];
    
    isDevicePositionFront = NO;
    self.backCameraInput = [[AVCaptureDeviceInput alloc] initWithDevice:device error:&error];
    if (error) {
        NSLog(@"%@",error);
    }
    self.stillImageOutput = [[AVCaptureStillImageOutput alloc] init];
    //输出设置。AVVideoCodecJPEG   输出jpeg格式图片
    NSDictionary * outputSettings = [[NSDictionary alloc] initWithObjectsAndKeys:AVVideoCodecJPEG,AVVideoCodecKey, nil];
    [self.stillImageOutput setOutputSettings:outputSettings];
    self.session = [[AVCaptureSession alloc] init];
    self.session.sessionPreset = AVCaptureSessionPresetInputPriority;
    
    if ([self.session canAddInput:self.backCameraInput]) {
        [self.session addInput:self.backCameraInput];
    }
    if ([self.session canAddOutput:self.stillImageOutput]) {
        [self.session addOutput:self.stillImageOutput];
    }
    
    //初始化预览图层
    self.previewLayer = [[AVCaptureVideoPreviewLayer alloc] initWithSession:self.session];
    self.previewLayer.frame = CGRectMake(0, 0, kScreenWidth, _preView.bounds.size.height);
    [self.previewLayer setVideoGravity:AVLayerVideoGravityResizeAspectFill];
    [_preView.layer addSublayer:self.previewLayer];
    
//    _imageView = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth, _preView.bounds.size.height)];
//    _imageView.contentMode = UIViewContentModeScaleAspectFill;
//    _imageView.clipsToBounds = YES;
//    [_preView addSubview:_imageView];
    
    UIPinchGestureRecognizer *pin = [[UIPinchGestureRecognizer alloc]initWithTarget:self action:@selector(zoomChangePinchGestureRecognizerClick:)];
    pin.delegate = self;
    [_preView addGestureRecognizer:pin];

}


//切换摄像头方向
- (void)changeCameraPositionWithCurrentIsFront:(BOOL)isFront {
    if (isFront) {
        [self.session stopRunning];
        [self.session removeInput:self.backCameraInput];
        if ([self.session canAddInput:self.frontCameraInput]) {
            [self.session addInput:self.frontCameraInput];
            [self.session startRunning];
        }
        
    } else {
        [self.session stopRunning];
        [self.session removeInput:self.frontCameraInput];
        if ([self.session canAddInput:self.backCameraInput]) {
            [self.session addInput:self.backCameraInput];
            [self.session startRunning];
        }
    }
}

//摄像头输入
- (AVCaptureDeviceInput *)backCameraInput {
    if (_backCameraInput == nil) {
        NSError *error;
        _backCameraInput = [[AVCaptureDeviceInput  alloc] initWithDevice:[self cameroWithPosition:AVCaptureDevicePositionBack] error:&error];
        if (error) {
            NSLog(@"后置摄像头获取失败");
        }
    }
    isDevicePositionFront = NO;
    return _backCameraInput;
}

- (AVCaptureDeviceInput *)frontCameraInput {
    if (_frontCameraInput == nil) {
        NSError *error;
        _frontCameraInput = [[AVCaptureDeviceInput alloc] initWithDevice:[self cameroWithPosition:AVCaptureDevicePositionFront] error:&error];
        if (error) {
            NSLog(@"前置摄像头获取失败");
        }
    }
    isDevicePositionFront = YES;
    return _frontCameraInput;
}

//获取可用的摄像头
- (AVCaptureDevice *)cameroWithPosition:(AVCaptureDevicePosition)position{
    
    if (@available(iOS 10, *)) {
        AVCaptureDeviceDiscoverySession *dissession = [AVCaptureDeviceDiscoverySession discoverySessionWithDeviceTypes:@[AVCaptureDeviceTypeBuiltInDuoCamera,AVCaptureDeviceTypeBuiltInTelephotoCamera,AVCaptureDeviceTypeBuiltInWideAngleCamera] mediaType:AVMediaTypeVideo position:position];
        for (AVCaptureDevice *device in dissession.devices) {
            if ([device position] == position ) {
                [device lockForConfiguration:nil];
                [device unlockForConfiguration];
                return device;
            }
        }
    } else {
        NSArray *devices = [AVCaptureDevice devicesWithMediaType:AVMediaTypeVideo];
        for (AVCaptureDevice *device in devices) {
            if ([device position] == position) {
                //更改这个设置的时候必须先锁定设备，修改完后再解锁，否则崩溃
                [device lockForConfiguration:nil];
                [device unlockForConfiguration];
                return device;
            }
        }
        
    }
    return nil;
    
}

//设置聚焦模式
- (BOOL)resetFocusAndExposureModes{
    AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
    AVCaptureExposureMode exposureMode = AVCaptureExposureModeContinuousAutoExposure;
    AVCaptureFocusMode focusMode = AVCaptureFocusModeContinuousAutoFocus;
    BOOL canResetFocus = [device isFocusPointOfInterestSupported] && [device isFocusModeSupported:focusMode];
    BOOL canResetExposure = [device isExposurePointOfInterestSupported] && [device isExposureModeSupported:exposureMode];
    CGPoint centerPoint = CGPointMake(0.5f, 0.5f);
    NSError *error;
    if ([device lockForConfiguration:&error]) {
        if (canResetFocus) {
            device.focusMode = focusMode;
            device.focusPointOfInterest = centerPoint;
        }
        if (canResetExposure) {
            device.exposureMode = exposureMode;
            device.exposurePointOfInterest = centerPoint;
        }

        [device unlockForConfiguration];
        return YES;
    }
    else{
        NSLog(@"%@", error);
        return NO;
    }
}


//-(void)shareAction{
//
//    AboutUsViewController * aboutUSView = [[AboutUsViewController alloc]init];
//    [self.navigationController pushViewController:aboutUSView animated:YES];
//
//}

//闪光灯
- (void)lightAction:(UIButton*)sender {
    sender.selected = !sender.selected;
    if (sender.selected) {
        //打开闪光灯
        AVCaptureDevice *captureDevice = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
        if ([captureDevice hasTorch]) {
            //更改这个设置的时候必须先锁定设备，修改完后再解锁，否则崩溃
            [captureDevice lockForConfiguration:nil];
            //设置闪光灯为自动
            [captureDevice setFlashMode:AVCaptureFlashModeOn];
            [captureDevice unlockForConfiguration];
        }
    }else{//关闭闪光灯
        AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
        if ([device hasTorch]) {
            [device lockForConfiguration:nil];
            //设置闪光灯为自动
            [device setFlashMode:AVCaptureFlashModeOff];
            [device unlockForConfiguration];
        }
    }
}

//切换摄像头
- (IBAction)changecapture:(id)sender {
    [self changeCameraPositionWithCurrentIsFront:!isDevicePositionFront];
}


//获取设备方向
-(AVCaptureVideoOrientation)avOrientationForDeviceOrientation:(UIDeviceOrientation)deviceOrientation
{
    AVCaptureVideoOrientation result = (AVCaptureVideoOrientation)deviceOrientation;
    if ( deviceOrientation == UIDeviceOrientationLandscapeLeft )
        result = AVCaptureVideoOrientationLandscapeRight;
    else if ( deviceOrientation == UIDeviceOrientationLandscapeRight )
        result = AVCaptureVideoOrientationLandscapeLeft;
    return result;
}

//相册
- (IBAction)retake:(id)sender {
    
    PhotoShowViewController *vc = [[PhotoShowViewController alloc]init];
    if (self.doubleButton.selected) {
        vc.isSelectTwo = YES;
    }
    else{
        vc.isSelectTwo = NO;
    }
    [self.navigationController pushViewController:vc animated:NO];
    
}

- (IBAction)doublechange:(id)sender {
    self.doubleButton = (UIButton*)sender;
    self.doubleButton.selected = !self.doubleButton.selected;
    if (self.doubleButton.selected) {
        [self maskView];
        isDoubleView = YES;
        self.maskView.hidden = NO;
        [self createSecondTipView]; //创建下面的提示拍照视图
    }
    else{
        //点击了单面
        isDoubleView = NO;
        [_showTopTakePhotoView removeFromSuperview];
        [_showSecondTakePhotoView removeFromSuperview];
        [self.session startRunning];
        _maskView.shwoView.image = nil;
        _maskView.shwoView2.image = nil;
        self.maskView.hidden = YES;
    }
}

-(UIImageView *)waterMarkImageView{
    
    if (_waterMarkImageView==nil) {
        _waterMarkImageView = [[UIImageView alloc]initWithFrame:_preView.frame];
        _waterMarkImageView.image = [UIImage waterMarkImageSize:CGSizeMake(_preView.frame.size.width*kwaterMarkFrameMultiple*kDeviceScale, _preView.frame.size.height*kwaterMarkFrameMultiple*kDeviceScale) andWaterMarkModel:nil];
        [_preView addSubview:_waterMarkImageView];
        _waterMarkImageView.hidden = YES;
    }
    
    return _waterMarkImageView;
}

/*
 *  加载双面选择的视图
 */
-(CupTwoView *)maskView{
    if (_maskView==nil) {
        WeakSelf;
        _maskView = [[CupTwoView alloc]initWithFrame:_preView.bounds];
        _maskView.takePhotoBlack = ^(ImageShowView *shwoView, BOOL first) {
            _currentSelectView = shwoView;
            if (first) {
                if (weakSelf.maskView.shwoView.isSetImage&&weakSelf.maskView.shwoView2.isSetImage) {
                    [weakSelf setGrayView:YES];
                }
                else{
                    if (!weakSelf.maskView.shwoView2.isSetImage) {
                        [weakSelf createSecondTipView];//显示拍照反面
                    }
                }
            }
            else{
                if (weakSelf.maskView.shwoView.isSetImage&&weakSelf.maskView.shwoView2.isSetImage) {
                    [weakSelf setGrayView:NO];
                }
                else{
                    if (!weakSelf.maskView.shwoView.isSetImage) {
                        [weakSelf createTopTipView];//显示拍照正面
                    }
                }
            }
        };
        _currentSelectView = _maskView.shwoView;
        UIPinchGestureRecognizer *pin = [[UIPinchGestureRecognizer alloc]initWithTarget:self action:@selector(zoomChangePinchGestureRecognizerClick:)];
        pin.delegate = self;
        [_maskView addGestureRecognizer:pin];
        [self.view addSubview:_maskView];
    }
    return _maskView;
}


/*
 *  创建提示层
 */
-(void)createTopTipView{
    [_showTopTakePhotoView removeFromSuperview];
    _showTopTakePhotoView = [[UIView alloc]initWithFrame:_maskView.WillCupRect];
    _showTopTakePhotoView.backgroundColor = [UIColor lightGrayColor];
    UILabel *label = [[UILabel alloc]initWithFrame:_showTopTakePhotoView.bounds];
    label.textAlignment = NSTextAlignmentCenter;
    label.text = @"拍照正面";
    label.textColor = [UIColor whiteColor];
    [_showTopTakePhotoView addSubview:label];
    
//    UILabel*showLabel = [[UILabel alloc]initWithFrame:CGRectMake(15, _showTopTakePhotoView.bounds.size.height-25, 200, 17)];
//    showLabel.textColor = [UIColor whiteColor];
//    showLabel.text = @"可旋转,可缩放";
//    [_showTopTakePhotoView addSubview:showLabel];
    
    [self.view addSubview:_showTopTakePhotoView];
    
    UITapGestureRecognizer*selectToptap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(selectToptapAction)];
    [_showTopTakePhotoView addGestureRecognizer:selectToptap];
}

/*
 *  点击手势作用与上面的拍照正面
 */
-(void)selectToptapAction{
    if (!_maskView.shwoView2.isSetImage) {
        //设置显示拍照反面
        [self createSecondTipView];
    }
    _currentSelectView = _maskView.shwoView;
    [_showTopTakePhotoView removeFromSuperview];
    if (self.session) {
        self.previewLayer.hidden = NO;
        [self.session startRunning];
    }
    [self focusAtPoint:_maskView.shwoView.center];
}


/*  创建提示层
 */
-(void)createSecondTipView{
    [_showSecondTakePhotoView removeFromSuperview];
    _showSecondTakePhotoView = [[UIView alloc]initWithFrame:_maskView.WillCupRect2];
    _showSecondTakePhotoView.backgroundColor = [UIColor lightGrayColor];
    UILabel *label = [[UILabel alloc]initWithFrame:_showSecondTakePhotoView.bounds];
    label.textAlignment = NSTextAlignmentCenter;
    label.text = @"拍照反面";
    label.textColor = [UIColor whiteColor];
    [_showSecondTakePhotoView addSubview:label];
//    UILabel*showLabel = [[UILabel alloc]initWithFrame:CGRectMake(15, _showSecondTakePhotoView.bounds.size.height-25, 200, 17)];
//    showLabel.textColor = [UIColor whiteColor];
//    showLabel.text = @"可旋转,可缩放";
//    [_showSecondTakePhotoView addSubview:showLabel];
    
    [self.view addSubview:_showSecondTakePhotoView];
    
    UITapGestureRecognizer*selectSecondtap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(selectSecondtapAction)];
    [_showSecondTakePhotoView addGestureRecognizer:selectSecondtap];
    
}

/*
 *  点击手势作用与下面的拍照反面
 */
-(void)selectSecondtapAction{
    if (!_maskView.shwoView.isSetImage) {
        //设置显示第一个拍照正面
        [self createTopTipView];
    }
    _currentSelectView = _maskView.shwoView2;
    [_showSecondTakePhotoView removeFromSuperview];
    if (self.session) {
        self.previewLayer.hidden = NO;
        [self.session startRunning];
    }
    [self focusAtPoint:_maskView.shwoView2.center];
    
}


//显示灰色视图
//是否是上层
-(void)setGrayView:(BOOL)istop{
    if (istop) {
        self.secondShowGrayView.hidden = NO;
    }
    else{
        self.showGrayView.hidden = NO;
    }
}

-(UIView *)showGrayView{
    if (_showGrayView==nil) {
        CGRect rect = _maskView.WillCupRect;
        //        rect.origin.y -=0.5;
        //        rect.size.height+=1;
        _showGrayView = [[UIView alloc]initWithFrame:rect];
        _showGrayView.backgroundColor = [UIColor colorWithWhite:0 alpha:0.5];
        [self.view addSubview:_showGrayView];
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(selectTopGraytapAction)];
        [_showGrayView addGestureRecognizer:tap];
    }
    return _showGrayView;
}

-(UIView *)secondShowGrayView{
    if (_secondShowGrayView==nil) {
        CGRect rect = _maskView.WillCupRect2;
        //        rect.origin.y -=0.5;
        //        rect.size.height+=1;
        _secondShowGrayView = [[UIView alloc]initWithFrame:rect];
        _secondShowGrayView.backgroundColor = [UIColor colorWithWhite:0 alpha:0.5];
        [self.view addSubview:_secondShowGrayView];
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(selectSecondGraytapAction)];
        [_secondShowGrayView addGestureRecognizer:tap];
    }
    return _secondShowGrayView;
}

/*
 *  点击手势作用与上面的选择相册
 */
-(void)selectTopGraytapAction{

    self.showGrayView.hidden = YES;
    self.secondShowGrayView.hidden = NO;
    _currentSelectView = _maskView.shwoView;

}

/*
 *  点击手势作用与下面的选择相册
 */
-(void)selectSecondGraytapAction{

    self.showGrayView.hidden = NO;
    self.secondShowGrayView.hidden = YES;
    _currentSelectView = _maskView.shwoView2;

}

//最小缩放值
- (CGFloat)minZoomFactor
{
    CGFloat minZoomFactor = 1.0;
    if (@available(iOS 11.0, *)) {
        AVCaptureDevicePosition position;
        if (isDevicePositionFront) {
            position = AVCaptureDevicePositionFront;
        }else{
            position = AVCaptureDevicePositionBack;
        }
        AVCaptureDevice *device = [self cameroWithPosition:position];
        minZoomFactor = device.minAvailableVideoZoomFactor;
    }
    return minZoomFactor;
}

//最大缩放值
- (CGFloat)maxZoomFactor
{
    AVCaptureDevicePosition position;
    if (isDevicePositionFront) {
        position = AVCaptureDevicePositionFront;
    }else{
        position = AVCaptureDevicePositionBack;
    }
    AVCaptureDevice *device = [self cameroWithPosition:position];
    CGFloat maxZoomFactor = device.activeFormat.videoMaxZoomFactor;
    if (@available(iOS 11.0, *)) {
        maxZoomFactor = device.maxAvailableVideoZoomFactor;
    }
    
    if (maxZoomFactor > 6.0) {
        maxZoomFactor = 6.0;
    }
    return maxZoomFactor;
}

- (BOOL)gestureRecognizerShouldBegin:(UIGestureRecognizer *)gestureRecognizer
{
    if ([gestureRecognizer isKindOfClass:[UIPinchGestureRecognizer class]]) {
        
        AVCaptureDevicePosition position;
        if (isDevicePositionFront) {
            position = AVCaptureDevicePositionFront;
        }else{
            position = AVCaptureDevicePositionBack;
        }
        AVCaptureDevice *device = [self cameroWithPosition:position];
        if ([gestureRecognizer isKindOfClass:[UIPinchGestureRecognizer class]]){
            self.currentZoomFactor = device.videoZoomFactor;
        }
    }
   
    return YES;
}

//缩放手势
- (void)zoomChangePinchGestureRecognizerClick:(UIPinchGestureRecognizer *)pinchGestureRecognizer
{
    AVCaptureDevicePosition position;
    if (isDevicePositionFront) {
        position = AVCaptureDevicePositionFront;
    }else{
        position = AVCaptureDevicePositionBack;
    }
     AVCaptureDevice *device = [self cameroWithPosition:position];
    if (pinchGestureRecognizer.state == UIGestureRecognizerStateBegan ||
        pinchGestureRecognizer.state == UIGestureRecognizerStateChanged)
    {
        CGFloat currentZoomFactor = self.currentZoomFactor * pinchGestureRecognizer.scale;
        
        if (currentZoomFactor < self.maxZoomFactor &&
            currentZoomFactor > self.minZoomFactor){
            
            NSError *error = nil;
            if ([device lockForConfiguration:&error] ) {
                device.videoZoomFactor = currentZoomFactor;
                [device unlockForConfiguration];
            }
            else {
                NSLog( @"Could not lock device for configuration: %@", error );
            }
        }
    }
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    UITouch *touch = touches.anyObject;
    CGPoint point = [touch locationInView:self.view];
    if (!isDoubleView) {
        //单张
        [self showfocus:point];
    }
    else{
        
//        if (CGRectContainsPoint(_showTopTakePhotoView.frame,point)) {
//            //触摸在tool层
//            return;
//        }
//        if (CGRectContainsPoint(_showSecondTakePhotoView.frame,point)) {
//            //触摸在tool层
//            return;
//        }
        [self showfocus:point];
    }
    
}


/*
 *  显示聚焦框
 */
-(void)showfocus:(CGPoint)point{
    if (_focusView) {
        [_focusView removeFromSuperview];
    }
    
    _focusView = [[UIImageView alloc]initWithFrame:CGRectMake(point.x, point.y, 0, 0)];
    _focusView.image = [UIImage imageNamed:@"focus"];
    [self.view addSubview:_focusView];
    
    [UIView animateWithDuration:0.2 animations:^{
        
        _focusView.frame =CGRectMake(point.x-20, point.y-20, 80, 80);
        
    } completion:^(BOOL finished) {
        
        _focusView.frame =CGRectMake(point.x-17, point.y-17, 61, 62);
        
        
    }];
    
    dispatch_time_t delayTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0/*延迟执行时间*/ * NSEC_PER_SEC));
    
    dispatch_after(delayTime, dispatch_get_main_queue(), ^{
        if (_focusView) {
            [_focusView removeFromSuperview];
        }
    });
    CGPoint fixpoint = [_previewLayer captureDevicePointOfInterestForPoint:point];
    
    NSLog(@"x===%d,y===%d",fixpoint.x,fixpoint.y);
    
    [self focusAtPoint:fixpoint];
    
}

//聚焦
- (void)focusAtPoint:(CGPoint)point {
    AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
    if ([self cameraSupportsTapToFocus] && [device isFocusModeSupported:AVCaptureFocusModeAutoFocus]) {
        NSError *error;
        if ([device lockForConfiguration:&error]) {
            device.focusPointOfInterest = point;
            device.focusMode = AVCaptureFocusModeAutoFocus;
            [device unlockForConfiguration];
        }
        else{
            NSLog(@"%@", error);
        }
    }
}

- (BOOL)cameraSupportsTapToFocus {
    return [[AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo] isFocusPointOfInterestSupported];
}

//拍照
- (IBAction)takePhotoButtonClick:(UIButton *)sender {
    
    _stillImageConnection = [self.stillImageOutput connectionWithMediaType:AVMediaTypeVideo];
    if(!_stillImageConnection){
        NSLog(@"拍照失败!");
        return;
    }
    
    UIDeviceOrientation curDeviceOrientation = [[UIDevice currentDevice] orientation];
    AVCaptureVideoOrientation avcaptureOrientation = [self avOrientationForDeviceOrientation:curDeviceOrientation];
    [_stillImageConnection setVideoOrientation:avcaptureOrientation];
//    [_stillImageConnection setVideoScaleAndCropFactor:self.effectiveScale];

    
    [self.stillImageOutput captureStillImageAsynchronouslyFromConnection:_stillImageConnection completionHandler:^(CMSampleBufferRef imageDataSampleBuffer, NSError *error) {

        if (imageDataSampleBuffer==nil) {
            return ;
        }

        [self.session stopRunning];
        NSData *imageData = [AVCaptureStillImageOutput jpegStillImageNSDataRepresentation:imageDataSampleBuffer];
        UIImage *image = [UIImage imageWithData:imageData];
        image = [Tools fixOrientation:image];
        
        //判断是单面还是双面
        if (!isDoubleView) {
            _imageView.image = image;
            _imageView.hidden = NO;
            image = [Tools imageFromImage:image atFrame:_preView.frame];
            
            //拍完照跳转到水印设置页面
            WatermarkContentViewController *vc = [[WatermarkContentViewController alloc]init];
            vc.headerImage = image;
            vc.isDoubleWaterMark = NO;
            [self.navigationController pushViewController:vc animated:YES];
        }
        else{
            //当前选择的是哪一个视图 上面还是下面的
            _currentSelectView.image = image;
            [self.session startRunning];
            
            //双面
            if ([_currentSelectView isEqual:_maskView.shwoView2]) {
                [MobClick event:@"double_take_photo_b"];//[双面 拍照b]
            }
            else{
                [MobClick event:@"double_take_photo_a"];//[双面 拍照a]
            }
            _currentSelectView.image = [image clipImageWithRect:[self changeToRect:_currentSelectView.frame]];
            
            if (_maskView.shwoView.isSetImage && _maskView.shwoView2.isSetImage) {
                
                BOOL showTopreturnBtn = NO;
                if (!_maskView.shwoView.backTopButton.hidden) {
                    _maskView.shwoView.backTopButton.hidden = YES;
                    showTopreturnBtn = YES;
                }
                _maskView.shwoView.layer.borderColor = [UIColor whiteColor].CGColor;
                UIImage *image = [Tools imageFromView:_maskView.shwoView];
                ViewBorderRadius(_maskView.shwoView, 0, 1, [UIColor colorWithRed:206/255.0 green:206/255.0 blue:206/255.0 alpha:1]);
                
                if (showTopreturnBtn) {
                    _maskView.shwoView.backTopButton.hidden = NO;
                }
                BOOL showsecondreturnBtn = NO;
                if (!_maskView.shwoView2.backTopButton.hidden) {
                    _maskView.shwoView2.backTopButton.hidden = YES;
                    showsecondreturnBtn = YES;
                }
                _maskView.shwoView2.layer.borderColor = [UIColor whiteColor].CGColor;
                UIImage *images = [Tools imageFromView:_maskView.shwoView2];
                ViewBorderRadius(_maskView.shwoView2, 0, 1, [UIColor colorWithRed:206/255.0 green:206/255.0 blue:206/255.0 alpha:1]);
                if (showsecondreturnBtn) {
                    _maskView.shwoView2.backTopButton.hidden = NO;
                }
                
                UIImage *finallImage = [Tools addImage:image toImage:images andSpace:_maskView.WillCupRect2.origin.y-CGRectGetMaxY(_maskView.shwoView.frame)];
                
                //拍完照跳转到水印设置页面
                WatermarkContentViewController *vc = [[WatermarkContentViewController alloc]init];
                vc.headerImage = finallImage;
                vc.isDoubleWaterMark = YES; 
                [self.navigationController pushViewController:vc animated:YES];
                
            }
            
            //如果需要自动拍双面的第二张,请在这边写...
            
        }
        
    }];
    
}

/*
 *  转换坐标
 */
-(CGRect)changeToRect:(CGRect)rect{
    return [_maskView convertRect:rect toView:[UIApplication sharedApplication].delegate.window];
}

//一张照片的点击事件
//- (IBAction)gotoBusinessLicenseVCAction:(UIButton *)sender {
//    
//    [MobClick event:@"single_entry"];//[首页 单面]

//        NSData *modelData = [[NSUserDefaults standardUserDefaults] objectForKey:kWaterMarkModel];
//        WaterMarkMode*model = [NSKeyedUnarchiver unarchiveObjectWithData:modelData];

//        if (model==nil||!model.isSetWaterMark) {
//            if (IOS11_OR_LATER) {
//                [self initOneView:self.view.safeAreaInsets];
//            }
//            else{
//                [self initOneView:UIEdgeInsetsZero];
//            }
//        }else{
    
//            BusinessLicenseViewController *vc = [[BusinessLicenseViewController alloc] init];
//            AppDelegate*dele = (AppDelegate*)[UIApplication sharedApplication].delegate;
//            dele.window.rootViewController = [[UINavigationController alloc]initWithRootViewController:vc];
//            [dele.window makeKeyAndVisible];

//            [self.navigationController pushViewController:vc animated:true];
////        }
//}

//相册选择的点击事件 打开相册
//- (IBAction)gotoPhotoChoseVCAction:(UIButton *)sender {
//
//    [MobClick event:@"album_entry"];//[首页 相册]
//    PhotoChoseViewController *vc = [[PhotoChoseViewController alloc] init];
//    [self.navigationController pushViewController:vc animated:true];
//
//}

///*
// *  弹框分享
// */
//-(void)popshareWithshareTitle:(NSString *)shareTitle{
//
//    PopClickView *view = [[PopClickView alloc]initWithShowFrame:self.view.bounds andAlpha:0.3];
//    view.label.text = shareTitle;
//    WeakSelf;
//    view.shareAction = ^{
//        [weakSelf shareAction];
//    };
//    [view show];
//}


//升级，跳转到App Store
//-(void)updateAction{
//    NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"https://itunes.apple.com/cn/app/id1328253837"]];
//    if (IOS10_OR_LATER) {
//        [[UIApplication sharedApplication] openURL:url options:@{} completionHandler:nil];
//    }
//    else{
//        [[UIApplication sharedApplication] openURL:url];
//    }
//}

@end
